<script setup lang="ts">
const dialogRef = $ref<DialogInstance>()
interface OnCloseResolveType {
  type: 'ok' | 'cancel'
  val: RuleForm | undefined
}

let onCloseResolve = function (_value: OnCloseResolveType) { }
async function showDialog() {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: '新增',
  })
  onCloseResolve = dialogRes.onCloseResolve
  return await dialogRes.dialogPrm
}

function cancel() {
  onCloseResolve({ type: 'cancel', val: undefined })
}
interface RuleForm {
  name: string
  sex: string
  birthday: string
  address?: string
  role?: string[]
}

const ruleForm = reactive<RuleForm>({
  name: '',
  sex: '0',
  birthday: '',
})
const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 6, max: 12, message: '用户名需要在6-12字', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' },
  ],
})

async function confirm(formEl: FormInstance | undefined) {
  if (!formEl)
    return
  await formEl.validate((valid) => {
    if (!valid) {
      Message({
        message: '请填写完整',
        type: 'error',
      })
      return
    }

    onCloseResolve({ type: 'ok', val: ruleForm })
  })
}

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    :before-close="cancel"
    @confirm="confirm(ruleFormRef)"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <sy-dict
          v-model="ruleForm.sex"
          dict-type="user_sex"
          type="radio"
        />
      </el-form-item>
      <el-form-item
        label="出生日期"
        prop="birthday"
        un-w-full
      >
        <el-date-picker
          v-model="ruleForm.birthday"
          style="width: 100%;"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="ruleForm.address" />
      </el-form-item>
    </el-form>
  </sy-dialog>
</template>

<style scoped></style>
